import { _decorator, Component, MeshRenderer, Node, random, randomRange, tween, v2, v3, Vec2, Vec3, Vec4 } from 'cc';
import { EventName } from 'db://assets/Scripts/Framework/Const/EventName';
import Events from 'db://assets/Scripts/Framework/Utils/Events';
import { InGameManager } from './InGameManager';
const { ccclass, property } = _decorator;

@ccclass('PoisonManager')
export class PoisonManager extends Component {

    private static instance: PoisonManager;
    public static get Instance(): PoisonManager {
        return this.instance;
    }


    @property(Node)
    curPoison: Node;

    @property(Node)
    nextPoison: Node;

    radius = 600;
    time = 0;
    round = 0;

    protected onLoad(): void {
        PoisonManager.instance = this;
    }

    start() {

    }

    update(deltaTime: number) {
        this.radius = this.curPoison.worldScale.x;
        if (this.time > 0) {
            this.time -= deltaTime;
            if (this.time <= 0) {
                this.time = 0;
                this.MovePoison();
            }
        }
    }

    CheckInNext(pos: Vec3): boolean {
        let poisonPos = this.nextPoison.getWorldPosition();
        pos.y = 0;
        poisonPos.y = 0;
        let dis = Vec3.distance(poisonPos, pos);
        return dis < this.radius / 2;
    }

    CheckInPoison(pos: Vec3): boolean {
        let poisonPos = this.curPoison.getWorldPosition();
        pos.y = 0;
        poisonPos.y = 0;
        let dis = Vec3.distance(poisonPos, pos);
        return dis < this.radius / 2;
    }

    MovePoison() {
        // return;
        this.round++;
        let radius = this.radius * 2 / 3;
        if (this.round == 6) radius = 0;
        tween(this.curPoison)
            .to(30, {
                worldPosition: this.nextPoison.getWorldPosition(),
                scale: v3(radius, 1000, radius)
            })
            .call(() => { if (this.round <= 5) this.MoveNextPoison(); }).start();
        InGameManager.Instance.ResetSpawn();
    }

    MoveNextPoison() {
        // return;
        let r = this.radius * 2 / 3;
        if (this.round == 5) r = 0;
        let v2Pos = v2();
        Vec2.random(v2Pos, randomRange(0, (this.radius - r) / 2));
        let pos = this.curPoison.getWorldPosition();
        if (this.round < 5) pos.add(v3(v2Pos.x, 0, v2Pos.y));
        this.nextPoison.setWorldPosition(pos);
        this.nextPoison.setWorldScale(Vec3.ONE.clone().multiplyScalar(r));
        this.time = 90;
        Events.emit(EventName.AIRestartNextPoison);
    }
}


